<template>
    <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="修理项目" name="fixitem">
            <el-table
                ref="tableRef"
                id="fixlist-table-fixlist"
                :data="tableData"
                v-bind="tableDefaultAttribute"
                row-key="id"
                :max-height="tableHeight"
                table-layout="auto"
                @row-dblclick="update"
                :summary-method="getSummaries"
                show-summary
            >
                <template #empty>
                    <span>无数据</span>
                </template>
                <el-table-column
                    type="selection"
                    width="55"
                    :align="'center'"
                />
                <template v-for="col in tableColumns" :key="col.prop">
                    <el-table-column
                        v-if="!col.isHidden"
                        :align="col.align"
                        :prop="col.prop"
                        :label="col.label"
                        :fixed="col.fixed"
                        :formatter="col.formatter"
                        :type="col.type"
                        :width="col.width"
                    >
                    </el-table-column>
                </template>
            </el-table>
            <el-button-group class="bg">
                <el-space>
                    <el-button v-if="caller === 'CfsCntrs'"
                        class="btn"
                        type="primary"
                        :icon="Plus"
                        @click="add"
                        >增加</el-button
                    >
                    <el-button v-if="caller === 'CfsCntrs'"
                        class="btn"
                        type="primary"
                        :icon="Delete"
                        @click="onDelete"
                        >删除</el-button
                    >
                </el-space>
            </el-button-group>
        </el-tab-pane>
        <el-tab-pane label="修理批复" name="fixmsg"> 
            <el-table
                ref="tableReplyRef"
                id="fixlist-table-replylist"
                :data="tableReplyData"
                v-bind="tableDefaultAttribute"
                row-key="id"
                :max-height="tableHeight"
                table-layout="auto"
            >
                <template #empty>
                    <span>无数据</span>
                </template>
                <el-table-column
                    type="selection"
                    width="55"
                    :align="'center'"
                />
                <template v-for="col in tableReplyColumns" :key="col.prop">
                    <el-table-column
                        v-if="!col.isHidden"
                        :align="col.align"
                        :prop="col.prop"
                        :label="col.label"
                        :fixed="col.fixed"
                        :formatter="col.formatter"
                        :type="col.type"
                        :width="col.width"
                    >
                    </el-table-column>
                </template>
            </el-table>
        </el-tab-pane>
    </el-tabs>

    <el-dialog
        v-model="dialogUpdateVisible"
        title="修箱"
        draggable
        destroy-on-close
        :center="true"
    >
        <NormalForm
            :formOptions="formOptions"
            :formItems="formItems"
            :formData="paramData"
            :createActionName="createActionName"
            :updateActionName="updateActionName"
            :unInitField="unInitFields"
            :rules="rules"
            @create="onAdded"
            @update="onUpdated"
            
        >
        </NormalForm>
    </el-dialog>
</template>
<script setup lang="ts" name="FixList">
import { ref, reactive, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import {
    isEmpty,
    
    forEach,
    
} from 'lodash';
import type {
    CntrFixItemModel,
    CntrFixReplyModel,
} from '@/common/types/container';
import {
    ElMessage,
    ElMessageBox,
    FormRules,
    TableInstance,
} from 'element-plus';
import { Plus, Delete } from '@element-plus/icons-vue';
import { Request } from '@/app/request';
import {
    tableDefaultAttribute,
    
    tableColumnDefault,
} from '@/hooks/useTable';
import { FormFieldItem, TableColumn } from '@/common/types/app';
import { useAppStore } from '@/store/app';
import { transFormatter } from '@/common/tools';
import {
    
    initObjectProperty,
    pickFormFromTable,
    
} from '@/common/tools';
import { formatDateTime } from '@/common/tools';

import NormalForm from '@/components/forms/NormalForm.vue';
const activeName = ref('fixitem');
const tableRef = ref<TableInstance>();
const tableReplyRef = ref<TableInstance>();
const tableData = ref<Array<CntrFixItemModel>>([]);
const tableReplyData = ref<Array<CntrFixReplyModel>>([]);
const total_money = ref(0);
const tableHeight = ref(100);
const paramData = reactive<CntrFixItemModel>({});
const props = defineProps<{
    cntr_no?: number;
    caller?: string;
}>();
const emit = defineEmits<{
    (e: 'yh-closedialog'): void;
}>();
const dialogUpdateVisible = ref(false);
const formOptions = reactive<{
    labelWidth?: string;
    labelPosition?: string;
}>({});
const createActionName = ref('箱修理项目增加');
const updateActionName = ref('箱修理项目修改');
const unInitFields = ['cntr_no'];

const rules = reactive<FormRules>({
    fix_item_nam: [
        { required: true, message: '请输入修理项目', trigger: 'blur' },
    ],
    total_money: [
        { required: true, message: '请选择成本中心', trigger: 'blur' },
    ],
});
const { SelectOptionReply } = storeToRefs(useAppStore());
const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: { value: string | number; label: string }[];
    if (column['property'] === 'reply_id') {
        data = SelectOptionReply.value;
    } else {
        return cellValue;
    }

    return transFormatter(cellValue, data);
};
const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'fix_item_nam',
        label: '修理描述',
        formFieldItemType: 'input',
        // width: 300,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'total_money',
        label: '修理金额',
        formFieldItemType: 'number',
        width: 150,
        formOption: {
            min: 0,
            max: Infinity,
        },
    },
]);
const tableReplyColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'msg_time',
        label: '时间',
        formatter: formatDateTime,
        formFieldItemType: 'datetime',
        width: 250,
        // width: 300,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'oper_name',
        label: '人员',
        formFieldItemType: 'input',
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 3,
        prop: 'reply_id',
        label: '状态',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: SelectOptionReply.value,
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 3,
        prop: 'msg',
        label: '内容',
        formFieldItemType: 'input',
        width: 400,
    },
]);
const formItems = reactive<Array<FormFieldItem>>(
    pickFormFromTable(tableColumns),
);
const onRefresh = async () => {
    const req = new Request('堆场箱修理查询', { cntr_no: props.cntr_no });
    const r = await req.post();
    if (!isEmpty(r.obj)) {
        tableData.value = r.obj.fixlists;
        total_money.value = r.obj.total_money;
        tableReplyData.value = r.ext;
    }
};
onMounted(async () => {
    tableHeight.value = Math.floor(window.innerHeight / 2);

    await onRefresh();
});
const add = () => {
    initObjectProperty(paramData);
    paramData.cntr_no = props.cntr_no;
    // console.log(paramData);

    // paramData.fix_item_nam = '123';
    // paramData.total_money = 100;
    // paramData.value.cntr_no = props.cntr_no;
    dialogUpdateVisible.value = true;
};
const update = (row: CntrFixItemModel) => {
    Object.assign(paramData, row);
    dialogUpdateVisible.value = true;
};
const onAdded = (data: CntrFixItemModel) => {
    // tableData.value.unshift(data);
    onRefresh();
};
const onUpdated = (data: CntrFixItemModel) => {
    /* const i = findIndex(tableData.value, (o) => {
        return o.id === data.id;
    });
    if (i > -1) {
        Object.assign(tableData.value[i], omit(data, ['id']));
    } else {
        ElMessage.error('修改失败');
    } */
    onRefresh();
};
const onDelete = async () => {
    const rows: Array<CntrFixItemModel> = tableRef.value?.getSelectionRows() || [];
    if (rows.length === 0) {
        ElMessage.info({
            message: '请选择要删除数据',
        });
        return;
    }
    const ids = Array<number>();

    forEach(rows, (v: CntrFixItemModel) => {
        ids.push(v.id as number);
    });

    const msg = '';
    const cr = await ElMessageBox.confirm(msg, '确认删除选中修理项目', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const req = new Request('箱修理项目删除', {
            ids,
            cntr_no: rows[0].cntr_no,
        });
        const r = await req.post();
        if (r.code > 100) {
            /* forEachRight(tableData.value, (v: CntrFixItemModel, i: number) => {
                if (includes(ids, v.id)) {
                    tableData.value.splice(i, 1);
                }
            }); */
            onRefresh();
        }
    }
};
const onCloseDialog = (arg: any) => {
    if (dialogUpdateVisible.value) {
        dialogUpdateVisible.value = false;
    }
};
const getSummaries = () => {
    return ['', '总金额：', `${total_money.value}`];
};
</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}
</style>
